package xinyu.customer;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;

import androidx.multidex.MultiDex;

import com.logos.common.MainActivity;
import com.logos.tool.DynamicTimeFormat;
import com.netease.nim.avchatkit.AVChatKit;
import com.netease.nim.avchatkit.config.AVChatOptions;
import com.netease.nim.avchatkit.model.ITeamDataProvider;
import com.netease.nim.avchatkit.model.IUserInfoProvider;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nim.uikit.api.UIKitOptions;
import com.netease.nim.uikit.business.contact.core.query.PinYin;
import com.netease.nim.uikit.business.team.helper.TeamHelper;
import com.netease.nim.uikit.business.uinfo.UserInfoHelper;
import com.netease.nim.uikit.common.ToastHelper;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.mixpush.MixPushService;
import com.netease.nimlib.sdk.uinfo.model.UserInfo;
import com.netease.nimlib.sdk.util.NIMUtil;
import com.scwang.smartrefresh.header.BezierCircleHeader;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.squareup.leakcanary.LeakCanary;

import java.util.HashMap;
import java.util.Map;

import me.jessyan.autosize.AutoSize;
import me.jessyan.autosize.AutoSizeConfig;
import me.jessyan.autosize.onAdaptListener;

import xinyu.customer.chat.NIMInitManager;
import xinyu.customer.chat.NimSDKOptionConfig;
import xinyu.customer.chat.event.ChatOnlineStateContentProvider;
import xinyu.customer.chat.mixpush.DemoPushContentProvider;
import xinyu.customer.chat.preference.UserPreferences;
import xinyu.customer.chat.session.SessionHelper;
import xinyu.customer.login.SplashActivity;
import xinyu.customer.util.SpConstant;

import xinyu.customer.cache.LoginCache;

public class JGApplication extends Application {
    public static final String CONV_TITLE = "conv_title";
    public static final int IMAGE_MESSAGE = 1;
    public static final int TAKE_PHOTO_MESSAGE = 2;
    public static final int TAKE_LOCATION = 3;
    public static final int FILE_MESSAGE = 4;
    public static final int TACK_VIDEO = 5;
    public static final int TACK_VOICE = 6;
    public static final int BUSINESS_CARD = 7;
    public static final int TACK_GIFT = 8;//赠送礼物
    public static final int TACK_CALL_VIDEO = 9;//视频通话
    public static final int TACK_CALL_VOICE = 10;//语音通话
    public static final int TACK_NONE = 0;//无操作
    public static final int SEND_GIFT_MSG = 11;//赠送礼物(聊天页面)
    public static final int TACK_CALL_REFRSH = 12;//刷新 视频语音消息
    public static final int SEND_HEART_MSG = 13;//爱心消息


    public static final int CLOSE_ACTIVITY = 44;//关闭页面后台
    public static final int MAI_POLL = 45;//下麦
    public static final int REFRESH_KTV_LIST = 46;//刷新ktv板块页面
    public static final int TI_SDK_INIT = 99;//美颜初始化

    public static final int REQUEST_CODE_SEND_FILE = 26;
    public static final int RESULT_CODE_ALL_MEMBER = 22;

    public static Map<Long, Boolean> isAtMe = new HashMap<>();
    public static Map<Long, Boolean> isAtall = new HashMap<>();
    public static long registerOrLogin = 1;
    public static final int REQUEST_CODE_TAKE_PHOTO = 4;
    public static final int REQUEST_CODE_SELECT_PICTURE = 6;
    public static final int REQUEST_CODE_CROP_PICTURE = 18;
    public static final int REQUEST_CODE_CHAT_DETAIL = 14;
    public static final int RESULT_CODE_FRIEND_INFO = 17;
    public static final int REQUEST_CODE_ALL_MEMBER = 21;
    public static final int RESULT_CODE_EDIT_NOTENAME = 29;
    public static final String NOTENAME = "notename";
    public static final int REQUEST_CODE_AT_MEMBER = 30;
    public static final int RESULT_CODE_AT_MEMBER = 31;
    public static final int RESULT_CODE_AT_ALL = 32;
    public static final int SEARCH_AT_MEMBER_CODE = 33;

    public static final int RESULT_BUTTON = 2;
    public static final int START_YEAR = 1900;
    public static final int END_YEAR = 2050;
    public static final int RESULT_CODE_SELECT_FRIEND = 23;

    public static final int REQUEST_CODE_SELECT_ALBUM = 10;
    public static final int RESULT_CODE_SELECT_ALBUM = 11;
    public static final int RESULT_CODE_SELECT_PICTURE = 8;
    public static final int REQUEST_CODE_BROWSER_PICTURE = 12;
    public static final int RESULT_CODE_BROWSER_PICTURE = 13;
    public static final int RESULT_CODE_SEND_LOCATION = 25;
    public static final int RESULT_CODE_SEND_FILE = 27;
    public static final int REQUEST_CODE_SEND_LOCATION = 24;
    public static final int REQUEST_CODE_FRIEND_INFO = 16;
    public static final int RESULT_CODE_CHAT_DETAIL = 15;
    public static final int ON_GROUP_EVENT = 3004;
    public static final String DELETE_MODE = "deleteMode";
    public static final int RESULT_CODE_ME_INFO = 20;

    public static final String DRAFT = "draft";
    public static final String GROUP_ID = "groupId";
    public static final String POSITION = "position";
    public static final String MsgIDs = "msgIDs";
    public static final String NAME = "name";
    public static final String ATALL = "atall";
    public static final String SEARCH_AT_MEMBER_NAME = "search_at_member_name";
    public static final String SEARCH_AT_MEMBER_USERNAME = "search_at_member_username";
    public static final String SEARCH_AT_APPKEY = "search_at_appkey";

    public static final String MEMBERS_COUNT = "membersCount";

    public static String PICTURE_DIR = "sdcard/XinYang/pictures/";
    private static final String JCHAT_CONFIGS = "JChat_configs";
    public static String FILE_DIR = "sdcard/XinYang/recvFiles/";
    public static String VOICE_DIR = "/mnt/sdcard/XinYang/voice/";
    public static String VIDEO_DIR = "/mnt/sdcard/XinYang/video/";

    public static String DOWNLOAD_DIR = "/mnt/sdcard/XinYang/download/";
    public static String GIFT_DIR = "/mnt/sdcard/XinYang/gift/";
    public static String GIFT_MP3_DIR = "/mnt/sdcard/XinYang/gift/mp3/";
    public static String PLUGIN_DIR = "/mnt/sdcard/XinYang/plugin/";
    public static String KTV_MP4_DIR = "/mnt/sdcard/XinYang/ktv/mp4/";


    public static String DB_DIR = "sdcard/XinYang/db";
    public static final String TARGET_ID = "targetId";
    public static final String ATUSER = "atuser";
    public static final String TARGET_APP_KEY = "targetAppKey";
    public static int maxImgCount;               //允许选择图片最大数
    public static final String GROUP_NAME = "groupName";

    public static Context context;


    private static JGApplication mInstance;
    private final String TAG = SpConstant.TAG_AGROA;

    /**
     * 权限认证接口token认证
     */
    private static String devoiceToken;


    public static JGApplication getInstance() {
        return mInstance;
    }

    public static Context getContext() {
        return context;
    }

    // static 代码段可以防止内存泄露
    static {
        // 设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator((context, layout) -> {
            // 全局设置主题颜色（优先级第二低，可以覆盖 DefaultRefreshInitializer 的配置，与下面的ClassicsHeader绑定）
            MaterialHeader header = new MaterialHeader(context);
            return header;
        });
        // 设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator((context, layout) -> {
            // 指定为经典Footer，默认是 BallPulseFooter
            ClassicsFooter footer = new ClassicsFooter(context);
            footer.setAccentColor(Color.parseColor("#000000")); //设置强调颜色
            footer.setPrimaryColor(Color.parseColor("#f5f5f5")); //设置主题颜色
            footer.setDrawableSize(20);
            return footer;
        });
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(newBase);
        MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        context = this.getApplicationContext();
        mInstance = this;
        LeakCanary.install(this);
        initAutoSize();
        //网易云信开始
        LoginCache.setContext(this);
        // 4.6.0 开始，第三方推送配置入口改为 SDKOption#mixPushConfig，旧版配置方式依旧支持。
        NIMClient.init(this, getLoginInfo(), NimSDKOptionConfig.getSDKOptions(this));

        if (NIMUtil.isMainProcess(this)){
            PinYin.init(this);
            PinYin.validate();
            initUIKit();
            // 初始化消息提醒
            NIMClient.toggleNotification(UserPreferences.getNotificationToggle());
            NIMInitManager.getInstance().init(true);
            // 初始化音视频模块
            initAVChatKit();
        }
    }

    /**
     * 初始化uikit
     */
    private void initUIKit() {
        NimUIKit.init(this, buildUIKitOptions());
        // IM 会话窗口的定制初始化。
        SessionHelper.init();

        // 添加自定义推送文案以及选项，请开发者在各端（Android、IOS、PC、Web）消息发送时保持一致，以免出现通知不一致的情况
        NimUIKit.setCustomPushContentProvider(new DemoPushContentProvider());

        NimUIKit.setOnlineStateContentProvider(new ChatOnlineStateContentProvider());

        NIMClient.getService(MixPushService.class).enable(true);
    }

    /**
     * 配置UIkit
     * @return
     */
    private UIKitOptions buildUIKitOptions() {
        UIKitOptions options = new UIKitOptions();
        // 设置app图片/音频/日志等缓存目录
        options.appCacheDir = NimSDKOptionConfig.getAppCacheDir(this) + "/app";

        return options;
    }

    private void initAVChatKit() {
        AVChatOptions avChatOptions = new AVChatOptions() {
            @Override
            public void logout(Context context) {
//                MainActivity.logout(context, true);
                ToastHelper.showToast(context,"提示退出登录");
            }
        };
        avChatOptions.entranceActivity = SplashActivity.class;
        avChatOptions.notificationIconRes = R.mipmap.ic_launcher_app;
        com.netease.nim.avchatkit.ActivityMgr.INST.init(this);
        AVChatKit.init(avChatOptions);

//        // 初始化日志系统
//        LogHelper.init();
        // 设置用户相关资料提供者
        AVChatKit.setUserInfoProvider(new IUserInfoProvider() {
            @Override
            public UserInfo getUserInfo(String account) {
                return NimUIKit.getUserInfoProvider().getUserInfo(account);
            }

            @Override
            public String getUserDisplayName(String account) {
                return UserInfoHelper.getUserDisplayName(account);
            }
        });
        // 设置群组数据提供者
        AVChatKit.setTeamDataProvider(new ITeamDataProvider() {
            @Override
            public String getDisplayNameWithoutMe(String teamId, String account) {
                return TeamHelper.getDisplayNameWithoutMe(teamId, account);
            }

            @Override
            public String getTeamMemberDisplayName(String teamId, String account) {
                return TeamHelper.getTeamMemberDisplayName(teamId, account);
            }
        });
    }



    public static LoginInfo loginInfo;

    public static void setLoginInfo(LoginInfo o) {
        loginInfo = o;
    }

    /**
     * 用户信息
     * @return
     */
    private LoginInfo getLoginInfo() {
        if (loginInfo != null) {
            return loginInfo;
        }
        // 从本地读取上次登录成功时保存的用户登录信息
        String account = SpConstant.getUserId();
        String token = getString(R.string.nim_app_id);

        if (!TextUtils.isEmpty(account) && !TextUtils.isEmpty(token)) {
            return new LoginInfo(account, token);
        } else {
            return null;
        }
    }





    /**
     * 适配初始化
     */
    private void initAutoSize() {
        AutoSize.initCompatMultiProcess(this);
        AutoSizeConfig.getInstance().setCustomFragment(false)
                .setOnAdaptListener(new onAdaptListener() {
                    @Override
                    public void onAdaptBefore(Object target, Activity activity) {
                        //使用以下代码, 可支持 Android 的分屏或缩放模式, 但前提是在分屏或缩放模式下当用户改变您 App 的窗口大小时
                        //系统会重绘当前的页面, 经测试在某些机型, 某些情况下系统不会重绘当前页面, ScreenUtils.getScreenSize(activity) 的参数一定要不要传 Application!!!
                        //AutoSizeConfig.getInstance().setScreenWidth(ScreenUtils.getScreenSize(activity)[0]);
                        //AutoSizeConfig.getInstance().setScreenHeight(ScreenUtils.getScreenSize(activity)[1]);
                    }

                    @Override
                    public void onAdaptAfter(Object target, Activity activity) {
                    }
                });
    }



}
